package org.seedltd.upms.service.impl.sys;

import java.io.Serializable;

import org.seedltd.base.exception.BusinessException;
import org.seedltd.core.base.BasePage;
import org.seedltd.core.utils.BeanUtils;
import org.seedltd.core.utils.SqlUtils;
import org.seedltd.upms.enums.EnableStatus;
import org.seedltd.upms.mapper.sys.SysParamMapper;
import org.seedltd.upms.model.sys.entity.SysParam;
import org.seedltd.upms.model.sys.form.SysParamForm;
import org.seedltd.upms.model.sys.form.SysParamSearchForm;
import org.seedltd.upms.model.sys.vo.SysParamVO;
import org.seedltd.upms.service.sys.SysParamService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import lombok.AllArgsConstructor;

/**
 * 参数管理带缓存的业务实现
 *
 * @author laizuan
 * @version 1.0
 * @since 2021/07/19
 */
@Service
@AllArgsConstructor
@CacheConfig(cacheNames = "SysParam")
public class SysParamServiceImpl implements SysParamService {
    private final SysParamMapper sysParamMapper;

    @Override
    public SysParam findById(Serializable id) {
        return sysParamMapper.selectById(id);
    }

    @Override
    @CacheEvict(key = "#form.paramKey")
    public boolean update(SysParamForm form) {
        return SqlUtils.u(sysParamMapper).updateById(form, form.getParamId());
    }

    @Override
    @CachePut(key = "#form.paramKey", unless = "#result.paramId == null")
    public SysParam add(SysParamForm form) {
        if (sysParamMapper.checkKeyExists(form.getParamKey()) != null) {
            throw new BusinessException("key 已存在，请重新输入！");
        }
        SysParam entity = new SysParam();
        BeanUtils.copyProperties(form, entity);
        sysParamMapper.insert(entity);
        return entity;
    }

    @Override
    @CacheEvict(key = "#key")
    public boolean deleteByKey(String key) {
        return SqlUtils.u(sysParamMapper).eq(SysParam::getParamKey, key).delete();
    }

    @Override
    @Cacheable(key = "#key", unless = "#result == null")
    public SysParam getByKey(String key) {
        return SqlUtils.q(sysParamMapper).eq(SysParam::getParamKey, key)
            .eq(SysParam::getEnabled, EnableStatus.ENABLE.getValue()).selectOne();
    }

    @Override
    public BasePage<SysParamVO> page(SysParamSearchForm searchForm) {
        return SqlUtils.q(sysParamMapper, searchForm).selectPage(searchForm.getStart(), searchForm.getSize(),
            SysParamVO.class);
    }
}